#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
using namespace std;

const int backlog = 10;

enum
{
    SOCKET_ERR = 2,
    BIND_ERR,
    LISTEN_ERR
};

class Sock // 封装TCP传输协议 socket套接字相关接口
{
public:
    Sock()
    {
    }
    ~Sock()
    {
    }

public:
    void Socket()
    {
        int _sockfd = socket(AF_INET, SOCK_STREAM, 0); // TCP
        if (_sockfd < 0)
        {
            cout << "socket error:" << errno << " " << strerror(errno) << endl;
            exit(SOCKET_ERR);
        }
    }
    void Bind(const uint16_t &port)
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = htons(INADDR_ANY);
        int n = bind(_listensockfd, (sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            exit(BIND_ERR);
        }
    }
    void Listen()
    {
        if (listen(_listensockfd, backlog) < 0)
        {
            exit(LISTEN_ERR);
        }
    }
    int Accept(string &clientip, uint16_t &clientport) // 获取客户端的新连接 clientip,clientport是输出型参数
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int sockfd = accept(_listensockfd, (sockaddr *)&client, &len);
        if(sockfd<0)
        {
            return -1;
        }
        clientport = ntohs(client.sin_port); // 网络字节序->主机字节序
        char ipstr[46];
        inet_ntop(AF_INET,&client.sin_addr,ipstr,sizeof(client));
        clientip = ipstr;
        return sockfd;
    }
    void Connect(const string& serverip, const uint16_t& serverport)//该接口用于TCP客户端
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;

        server.sin_addr.s_addr = inet_aton(serverip.c_str(),&server.sin_addr);//主机字符串ip->网络字节序ip
        server.sin_port = htons(serverport);

        connect(_listensockfd,(sockaddr*)&server,sizeof(server));
    }
    void Close()
    {
        close(_listensockfd);
    }
    int Fd()
    {
        return _listensockfd;
    }

private:
    int _listensockfd;
};